package io.aggression.test.util;


import io.aggression.test.model.User;
import io.undertow.security.api.AuthenticationMechanism;
import io.undertow.security.api.AuthenticationMode;
import io.undertow.security.handlers.AuthenticationCallHandler;
import io.undertow.security.handlers.AuthenticationConstraintHandler;
import io.undertow.security.handlers.AuthenticationMechanismsHandler;
import io.undertow.security.handlers.SecurityInitialHandler;
import io.undertow.security.idm.Account;
import io.undertow.security.idm.IdentityManager;
import io.undertow.security.impl.BasicAuthenticationMechanism;
import io.undertow.security.impl.DigestAuthenticationMechanism;
import io.undertow.server.HttpHandler;

import java.security.Principal;
import java.util.Collections;
import java.util.List;
import java.util.Set;


public final class Security {

	public static final String SECURITY_REALM_NAME = "Aggression Labs";

	public static Account getAccountFromUser( final User user){

		return new Account(){
			@Override
			public Principal getPrincipal() {
				return principal;
			}

			@Override
			public Set<String> getRoles() {
				return Collections.emptySet();
			}

			private final Principal principal = new Principal(){

				@Override
				public String getName() {
					return user.getUserId();
				}
			};
		};


	}

	public static HttpHandler wrapHandler(HttpHandler toWrap, final IdentityManager identityManager){
	//	public static HttpHandler wrapHandler(final HttpHandler toWrap, final IdentityManager identityManager){

		HttpHandler handler = toWrap;

		handler = new AuthenticationCallHandler(handler);
		handler = new AuthenticationConstraintHandler(handler);

		//final List<AuthenticationMechanism> mechanisms = Collections.<AuthenticationMechanism>singletonList(new BasicAuthenticationMechanism(SECURITY_REALM_NAME));
		final List<AuthenticationMechanism> mechanisms = Collections.<AuthenticationMechanism>singletonList(new DigestAuthenticationMechanism(SECURITY_REALM_NAME,"aggression.io","MD5"));
		handler = new AuthenticationMechanismsHandler(handler, mechanisms);
		handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler);

		return handler;
	}


}
